package service

import (
	"errors"
	"shoping.zozoo.net/dao"
	"shoping.zozoo.net/model"
	"shoping.zozoo.net/params"
	"shoping.zozoo.net/tool"
)

type UserInterface interface {
	Create(*params.UserParam) (int64, error)
	Login(*params.UserLogin) (*model.User, error)
}

type UserVice struct {
	dao dao.UserInterface
}

func NewUserService(d dao.UserInterface) UserInterface {
	return &UserVice{
		d,
	}
}

//创建用户
func (u *UserVice) Create(param *params.UserParam) (id int64, err error) {

	var (
		user *model.User
	)

	user = &model.User{}

	//判断用户名是否存在
	if user, err = u.dao.FindByUserName(param.UserName); err != nil && err.Error() != "用户不存在" {
		return 0, err
	}

	if user.Id > 0 {
		return 0, errors.New("用户名存在")
	}

	//密码加密
	user.UserName = param.UserName
	user.NickName = param.NickName
	user.Password = tool.MD5(param.Password)

	if id, err = u.dao.Create(user); err != nil {
		return 0, err
	}

	return
}

//查找用户
func (u *UserVice) Login(param *params.UserLogin) (user *model.User, err error) {

	user = new(model.User)
	if user, err = u.dao.FindByUserName(param.UserName); err != nil {
		return nil, err
	}

	//密码加密
	param.UserName = tool.MD5(param.UserName)

	//比对密码是否一致
	if user.Password != param.UserName {
		return nil, errors.New("密码错误")
	}

	return
}
